#!/usr/bin/env python
import threading
import os
import dieu.settings, dieu.bookmark, dieu.database

def threaded(f):
    def wrapper(*args):
        t = threading.Thread(target=f, args=args)
        t.start()
    return wrapper

@threaded
def sync():
    for user in dieu.settings.get_users():
        online = dieu.bookmark.DieuWebBookmarks(user.split(':')[0], dieu.settings.get_password(user.split(':')[0], user.split(':')[1]), user.split(':')[1])
        if online.check_status() != dieu.settings.get_status(user.split(':')[0], user.split(':')[1]):
            onlineposts = online.get_posts()
            onlineposts.reverse()
            
            database = dieu.database.DieuDatabase(user.split(':')[0], user.split(':')[1])
            databaseposts = database.get_all_posts('Default')
            databasetags = database.get_all_tags('Default')
            
            onlineurls = []
            for post in onlineposts:
                onlineurls.append(post[1])
            
            databaseurls = []
            for post in databaseposts:
                databaseurls.append(post[2])
            
            neededurls = []
            for url in onlineurls:
                if url in databaseurls:
                    pass
                else:
                    neededurls.append(url)
            
            for post in onlineposts:
                if post[1] in neededurls:
                    database.add_post(post[0], post[1], post[2], post[3])
            
            database = dieu.database.DieuDatabase(user.split(':')[0], user.split(':')[1])
            databaseposts = database.get_all_posts('Default')
            databasetags = database.get_all_tags('Default')
            
            dbtags = []
            for tag in databasetags:
                dbtags.append(tag[1])
            
            addedtags = []
            for post in databaseposts:
                for tag in post[3].split(' '):
                    if tag in dbtags:
                        pass
                    else:
                        addedtags.append(tag)
            
            justaddedtags = []
            for tag in addedtags:
                if tag in justaddedtags:
                    pass
                else:
                    database.add_tag(tag)
                    justaddedtags.append(tag)
            
            dieu.settings.set_status(user.split(':')[0], user.split(':')[1], online.check_status())
            
            print 'Finished for '+user

